package com.yaofeng.mybatis.modules.sys.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yaofeng.mybatis.annotation.Log;
import com.yaofeng.mybatis.common.ErrorCodeEnum;
import com.yaofeng.mybatis.common.PageInfo;
import com.yaofeng.mybatis.common.ResponseInfo;
import com.yaofeng.mybatis.exception.BusinessException;
import com.yaofeng.mybatis.modules.sys.entity.User;
import com.yaofeng.mybatis.modules.sys.entity.UserPost;
import com.yaofeng.mybatis.modules.sys.entity.UserRole;
import com.yaofeng.mybatis.modules.sys.service.IMenuService;
import com.yaofeng.mybatis.modules.sys.service.IUserPostService;
import com.yaofeng.mybatis.modules.sys.service.IUserRoleService;
import com.yaofeng.mybatis.modules.sys.service.IUserService;
import com.yaofeng.mybatis.util.Sha256Util;
import com.yaofeng.mybatis.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yaofeng
 * @since 2019-08-30
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserPostService iUserPostService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IMenuService    iMenuService;


    /**
     * 查看用户列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    @RequiresAuthentication
    @Log(value = "用户列表")
    public ResponseInfo list(@RequestParam Map<String, Object> params, @RequestParam(defaultValue = "1") Long pageNum, @RequestParam(defaultValue = "50") Long pageSize) {
        IPage<User> page = iUserService.selectPage(new Page<>(pageNum, pageSize), params);
        List<User> userList = page.getRecords();
        userList.forEach(item -> {
            // 去掉密码和盐值信息
            item.setSalt("");
            item.setUserPassword("");
            // 身份证 加*处理
            if (StringUtils.isNotEmpty(item.getIdCard())) {
                item.setIdCard(StringUtil.idCardMask(item.getIdCard(), 10, 5));
            }
        });
        return ResponseInfo.success(new PageInfo(page));
    }



    @GetMapping("/btn/perms/list")
    @RequiresAuthentication
    @Log(value = "查看用户按钮权限信息")
    public ResponseInfo  getUserPtnPerms(@RequestParam("userId") Long userId){
       List<String>  btnPerms = iMenuService.getBtnPermsByUserId(userId);
        return ResponseInfo.success(btnPerms);
    }


    /**
     * 查看用户相关的角色和岗位信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/post/role/list")
    @RequiresAuthentication
    @Log(value = "查看用户相关的角色和岗位信息")
    public ResponseInfo getUserPostsAndUserRoles(@RequestParam("userId") Long userId) {
        List<UserPost> userPosts = iUserPostService.list(Wrappers.<UserPost>lambdaQuery().eq(UserPost::getUserId, userId));
        List<String> postIdList = userPosts.stream().map(u -> u.getPostId().toString()).collect(Collectors.toList());
        List<UserRole> userRoles = iUserRoleService.list(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, userId));
        List<String> roleIdList = userRoles.stream().map(u -> u.getRoleId().toString()).collect(Collectors.toList());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("postIds", postIdList);
        jsonObject.put("roleIds", roleIdList);
        return ResponseInfo.success(jsonObject);
    }


    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    @RequiresAuthentication
    @Log(value = "保存用户")
    public ResponseInfo save(@RequestBody @Valid User user) {
        iUserService.saveUser(user);
        return ResponseInfo.success();
    }

    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    @RequiresAuthentication
    @Log(value = "更新用户")
    public ResponseInfo update(@RequestBody @Valid User user) {
        iUserService.updateUser(user);
        return ResponseInfo.success();
    }

    /**
     * 更新用户状态
     *
     * @param user
     * @return
     */
    @PutMapping("/status")
    @RequiresAuthentication
    @Log(value = "更新用户状态")
    public ResponseInfo editStatus(@RequestBody @Valid User user) {
        User editUser = User.builder().status(user.getStatus()).userId(user.getUserId()).build();
        iUserService.updateById(editUser);
        return ResponseInfo.success();
    }

    /**
     * 更新用户密码
     *
     * @param user
     * @return
     */
    @PutMapping("/password")
    @RequiresAuthentication
    @Log(value = "更新用户密码")
    public ResponseInfo editPassword(@RequestBody @Valid User user) {
        User editUser = iUserService.getById(user.getUserId());
        if (editUser == null) {
            throw new BusinessException(ErrorCodeEnum.LOGIN_NAME__ERROR);
        }
        String salt = editUser.getSalt();
        editUser = User.builder().userPassword(Sha256Util.encoder(user.getUserPassword(), salt)).userId(user.getUserId()).build();
        iUserService.updateById(editUser);
        return ResponseInfo.success();
    }


    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    @RequiresAuthentication
    @Log(value = "删除用户")
    public ResponseInfo delete(Long id) {
        iUserService.deleteUser(id);
        return ResponseInfo.success();
    }


}
